package com.excel;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.SQLException;

import jxl.format.Alignment;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.write.Border;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.NumberFormats;
import jxl.write.VerticalAlignment;
import jxl.write.WritableCellFormat;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.lexer.Lexer;
import org.htmlparser.tags.Div;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.excel.read.ExcelConfig;
import com.excel.read.ExcelTableConfig;
import com.mike.excel.TestTableConfig;

/**
 * @author mike
 * 
 */
public class ComplexTableExcelWriter extends MExcelWriter {
	/**
	 * head and data
	 */
	String htmlTable;
	TableRow[] trList;

	public static Node extractCondition(NodeList list, String id) {
		int size = list.size();
		Node aNode = null;
		for (int i = 0; i < size; i++) {
			Node node = list.elementAt(i);
			if (node instanceof Div) {
				Div divTag = (Div) node;
				String anId = divTag.getAttribute("id");
				if (anId != null && anId.equalsIgnoreCase(id)) {
					aNode = node;
					return aNode;
				}
			}
		}

		return aNode;

	}

	public static Node extractTable(NodeList list, String id) {
		int size = list.size();
		Node node = null;
		Node aNode = null;

		aNode = list.elementAt(0);
		return aNode;

	}

	public ComplexTableExcelWriter(String fileName, String htmlTable, String condition) {
		super(fileName);
		this.htmlTable = htmlTable;
	}

	private TableTag extracTable(NodeList alist) {
		NodeClassFilter rorFilter = new NodeClassFilter(TableTag.class);
		// 得到所有经过过滤的标签
		NodeList list = alist.extractAllNodesThatMatch(rorFilter, true);
		for (int i = 0; i < list.size(); i++) {
			return (TableTag) list.elementAt(i);
		}
		return null;
	}

	/**
	 * 通过HTML Table设置配置信息
	 */
	public void initConfig() {


		Lexer lexer = new Lexer(htmlTable);
		
		Parser parser = new Parser(lexer);
		TableRow[] ast2 = null;

		try {
			NodeList list = parser.parse(null);
			TableTag aTableTag = extracTable(list);
			ast2 = aTableTag.getRows();
			this.trList = ast2;
			dataRowCount = this.trList.length;
		} catch (ParserException e1) {
			e1.printStackTrace();
		}

	}

	protected void drawRect(BorderLineStyle style, Colour BorderColor,
			Colour bgColor) throws WriteException {
	}

	/**
	 * 判断字符串是否是整数
	 */
	public static boolean isInteger(String value) {
		try {
			Integer.parseInt(value);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	/**
	 * 判断字符串是否是浮点数
	 */
	public static boolean isDouble(String value) {
		try {
			Double.parseDouble(value);
			if (value.contains("."))
				return true;
			return false;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	/**
	 * 判断字符串是否是数字
	 */
	public static int getNumberFlag(String value) {
		int falg = 0;
		if (isDouble(value)) {
			falg = 1;
		} else if (isInteger(value)) {
			falg = 2;
		}
		return falg;
	}

	public TableModel getTableModel() {
		int rowLen = this.trList.length;
		int colLen = getColLen();
		TableModel aTableModel = new TableModel(rowLen, colLen);
		for (int i = 0; i < rowLen; i++) {
			int curColLen = 0;
			TableRow trElement = this.trList[i];
			TableColumn[] tdElementsList = trElement.getColumns();
			int numColumns = tdElementsList.length;
			for (int j = 0; j < numColumns; j++) {
				TableColumn tdElement = tdElementsList[j];
				if(i==14) {
					int a= 99;
				}
				aTableModel.setCell(i, tdElement);// 填充单元格
			}
		}
		return aTableModel;
	}

	public int getColLen() {
		int rowLen = this.trList.length;
		int maxColLen = 0;
		for (int i = 0; i < rowLen; i++) {
			int curColLen = 0;
			TableRow trElement = this.trList[i];
			TableColumn[] tdElementsList = trElement.getColumns();
			int numColumns = tdElementsList.length;
			for (int j = 0; j < numColumns; j++) {
				TableColumn tdElement = tdElementsList[j];
				String colsSpanStr = tdElement.getAttribute("colspan");
				int colLen = colsSpanStr == null ? 1 : Integer
						.parseInt(colsSpanStr);
				curColLen += colLen;
			}
			if (curColLen > maxColLen) {
				maxColLen = curColLen;
			}
		}
		return maxColLen;
	}

	public void fillCells() {

	}

	/**
	 * 起始位置从(2,0)开始 * 1计算行数与列数 2迭代每一行，计算行号 3迭代每一个单元格，
	 * 4计算其跨行与跨列数，计算跨列的叠加值，计算起点单元格位置 5填值，画线。
	 */
	protected void writeDataSheet() {
		int rows = 0;
		// 标题列颜色
		String color = "#eeeeee";
		boolean isComplexHead = false;
		// 1.0取字段列表

		int numColumns = 0;
		// 判断猎头是否为两行

		// 得到模型
		TableModel aTM = getTableModel();
		try {
			// 逐行写数据
			// i为行号
			int i = 0;
			int colDlt = 0;// 列的迭代累加
			for (i = 0; i < dataRowCount; i++) {
				TableRow trElement = this.trList[i];

				TableColumn[] tdElementsList = trElement.getColumns();
				numColumns = tdElementsList.length;
				for (int j = 0; j < numColumns; j++) {
					// td
					TableColumn tdElement = tdElementsList[j];

					NodeList childList = tdElement.getChildren();
					String contentString = childList == null ? "" : childList
							.asString().replaceAll("&nbsp;", "");
					String colsSpanStr = tdElement.getAttribute("colspan");
					String rowSpanStr = tdElement.getAttribute("rowspan");
					int aRowIndex = Integer.parseInt(tdElement
							.getAttribute("rowIndex"));
					int aColIndex = Integer.parseInt(tdElement
							.getAttribute("colIndex"));

					int colLen = colsSpanStr == null ? 1 : Integer
							.parseInt(colsSpanStr);
					int rowLen = rowSpanStr == null ? 1 : Integer
							.parseInt(rowSpanStr);

					int flag = getNumberFlag(contentString);
					// 样式设定
					BorderLineStyle style = BorderLineStyle.THIN;
					Colour BorderColor = Colour.BLACK;

					WritableCellFormat alignStyle = new WritableCellFormat(); // 单元格样式

					alignStyle.setVerticalAlignment(VerticalAlignment.CENTRE);// 设置对齐方式
					alignStyle.setBorder(Border.TOP, style, BorderColor);// 设置边框的颜色和样式
					alignStyle.setBorder(Border.LEFT, style, BorderColor);// 设置边框的颜色和样式
					alignStyle.setBorder(Border.RIGHT, style, BorderColor);// 设置边框的颜色和样式
					alignStyle.setBorder(Border.BOTTOM, style, BorderColor);// 设置边框的颜色和样式

					// 如果是标题列，加背景, 设置默认对齐方式
					// 单元格对齐属性

					String align = tdElement.getAttribute("align");

					Alignment dataAlignment = Alignment.LEFT;
					Alignment titleAlignment = Alignment.CENTRE;

					if (align != null && align.equalsIgnoreCase("center")) {
						dataAlignment = Alignment.CENTRE;
						titleAlignment = Alignment.CENTRE;
					} else if (align != null && align.equalsIgnoreCase("right")) {
						dataAlignment = Alignment.RIGHT;
						titleAlignment = Alignment.RIGHT;
					} else if (align != null && align.equalsIgnoreCase("left")) {
						dataAlignment = Alignment.LEFT;
						titleAlignment = Alignment.LEFT;
					}

					if (isComplexHead) {
						if (i < 2) {
							// 标题
							alignStyle.setBackground(Colour.GREY_25_PERCENT); // TAN
							alignStyle.setAlignment(titleAlignment); // 设置对齐方式
						} else {
							// 数据
							alignStyle.setAlignment(dataAlignment); // 设置对齐方式
						}
						// 取得宽度
						if (i == 1) {
							String width = tdElement.getAttribute("width");
							if (width == null) {
								width = "60";
							} else if (width.indexOf("%") > -1) {
								width = width.replace("%", "");
								width = "" + Integer.parseInt(width) * 750;
							} else {
								width = width.replace("px", "");
							}
							s.setColumnView(j, Integer.parseInt(width) / 5);
						}
					} else {
						if (i == 0) {
							// 标题
							// 取得宽度
							String width = tdElement.getAttribute("width");
							if (width == null) {
								width = "60";
							} else if (width.indexOf("%") > -1) {
								width = width.replace("%", "");
								width = "" + Integer.parseInt(width) * 750;
							} else {
								width = width.replace("px", "");
							}
							s.setColumnView(j, Integer.parseInt(width) / 5);
							alignStyle.setAlignment(titleAlignment); // 设置对齐方式
							alignStyle.setBackground(Colour.GREY_25_PERCENT);
						} else {
							// 数据
							alignStyle.setAlignment(dataAlignment); // 设置对齐方式
						}
					}

					// 设置单元格的值
					if (flag == 1) {
						WritableCellFormat cf2 = new WritableCellFormat(
								NumberFormats.FLOAT);
						cf2.setAlignment(Alignment.LEFT);
						Number n = new Number(tableXIndex + aColIndex,
								tableYIndex + aRowIndex, Double
										.parseDouble(contentString), cf2);
						n.setCellFormat(alignStyle);
						s.addCell(n);
					} else if (flag == 2) {
						WritableCellFormat cf2 = new WritableCellFormat(
								NumberFormats.INTEGER);
						Number n = new Number(tableXIndex + aColIndex,
								tableYIndex + aRowIndex, Integer
										.parseInt(contentString), cf2);
						n.setCellFormat(alignStyle);
						s.addCell(n);
					} else {
						Label label = new Label(tableXIndex + aColIndex,
								tableYIndex + aRowIndex, contentString);

						label.setCellFormat(alignStyle);
						s.addCell(label);
					}

					if (colLen > 1 || rowLen > 1) {
						s.mergeCells(tableXIndex + aColIndex, tableYIndex
								+ aRowIndex, tableXIndex + aColIndex + colLen
								- 1, tableYIndex + aRowIndex + rowLen - 1);
					}
				}

			}
		} catch (RowsExceededException e) {
			e.printStackTrace();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (WriteException e) {
			e.printStackTrace();
		}

	}




	
	public static void main(String args[]) {
		
		ExcelTableConfig gridSearchConfig = new ExcelTableConfig();
		gridSearchConfig.tableConfig("d:\\x.xls");
		
		TestTableConfig.readFormatTable();
//		String data = "<table><tr><td>ds</td><td colspan=2>ds</td></tr><tr><td>ds</td><td>ds</td><td>ds</td></tr><table>";
//		MExcelWriter excelWrite = new ComplexTableExcelWriter("", data, "");
//		excelWrite.setTableDisplayName("ds");
//		excelWrite.setSheetName("查询");
//		try {
//			OutputStream os = new FileOutputStream("d:\\x.xls");
//			excelWrite.init(os);
//			excelWrite.writeExcel();
//			excelWrite.exit();
//
//		} catch (WriteException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}

	}
}
